<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-06 13:07:07
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;

use App\Http\Services\Service;
use App\Models\MpcBacthStorage;
use App\Models\MpcSummaryStorage;
use App\Repositories\MarketComplaintRepository;
use App\Repositories\MarketBackwarehouseDetailsPackRepository;
use App\Repositories\MarketBackwarehouseRepository;
use App\Repositories\MarketBackwarehouseDetailsRepository;
use App\Repositories\ProProcessesWipRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property MarketBackwarehouseRepository $repository
 * @property MarketBackwarehouseDetailsRepository $details  
 * @property MarketBackwarehouseDetailsPackRepository $pack  
 */
class BackwarehouseService extends Service
    {
    public function boot(
        MarketBackwarehouseRepository $repository,
        MarketBackwarehouseDetailsRepository $details,
        MarketBackwarehouseDetailsPackRepository $pack,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        $this->pack       = $pack;
        }
    public function details()
        {
        // DB::enableQueryLog();
        $data = $this->details->where("is_draft", 0)->condition(request())->getGrid();
        // dd(DB::getQueryLog());
        return $data;
        }
    public function info()
        {
        return $this->repository
            ->setRelation(['customer', 'carry' => ['company'], 'car' => ['company'], 'details' => ['material', 'location', 'packs']])
            ->condition(request())
            ->getOne();
        }

    public function list()
        {
        return $this->repository->condition(request())->getGrid();
        }
    public function pack()
        {
        return $this->pack->condition(request())->getGrid();
        }

    protected function save()
        {
        $data = request()->toArray();

        $code = $data['code'] ?? "";
        if ($code != "") {
            $gdata = $this->repository->whereCode($code)->getOne();

            if ($gdata->status_id != '0') {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            }
        $data['status_id'] = 0;
        if (count($data['details'] ?? []) == 0) {
            fail("订单状态明细不能为空！");
            }
        $data['is_draft'] = 0;
        //合计订单包/重
        $se_quantity                = $quantity = $auxiliary_quantity = 0;
        $data['details']            = array_map(function ($v) use ($data, &$quantity, &$se_quantity, &$auxiliary_quantity, )
            {
            $quantity += $v['quantity'];
            $v['red_quantity']     = $v['quantity'];
            $auxiliary_quantity += $v['auxiliary_quantity'];
            $v['main_customer_id'] = $data['customer_id'];
            $v['is_draft'] = 0;
            unset(
                $v['in_quantity'],
                $v['in_auxiliary_quantity'],
                $v['occupy_quantity'],
                $v['occupy_auxiliary_quantity'],
                $v['out_quantity'],
                $v['out_auxiliary_quantity'],
                $v['available_quantity'],
                $v['available_auxiliary_quantity'],
                $v['company_id'],
                $v['price'],
                $v['pro_dept_id'],
                $v['process_id'],
                $v['outfactory_id'],
                $v['open_card_id'],
                $v['faultle_quantity'],
                $v['is_scrap'],
                $v['direction_id'],
                $v['direction_process_id'],
                $v['feeding_ratio'],
                $v['hank']
            );
            return $this->details->autosave($v);
            }, $data['details']);
        $data['quantity']           = $quantity;
        $data['auxiliary_quantity'] = $auxiliary_quantity;
        $gdata['department_id']     = auth()->user()->department_id;
        $gdata                      = $this->repository->autosave($data);

        $this->saveCar($gdata);
        $this->saveCarry($gdata);
        $gdata->details->filter(function ($v) use ($gdata)
            {
            $v->code          = $gdata->code;
            $v->salesman_id   = $gdata->salesman_id;
            $v->department_id = $gdata->department_id;
            $v->billdate      = $gdata->billdate;
            $v->attachment    = $gdata->attachment;
            $v->save();
            });
        return true;
        }
    private function saveCarry($model)
        {
        $model->details->filter(function ($row) use ($model)
            {
            if ($model->carry_id == $row->carry_id)
                return;
            else if ($row->carry_id > 0)
                $row->removeCarryItem();

            if ($model->carry_id > 0)
                $row->addCarryItem($model->carry_id, $row->main->code);

            });
        }
    private function saveCar($model)
        {

        $model->details->filter(function ($row) use ($model)
            {
            if ($model->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();
            if ($model->car_id > 0)
                $row->addCarItem($model->creator->department?->name ?? "JG", $model->customer->name, $model->car_id);
            });
        }

    protected function audit()
        {
        $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })
            ->get()
            ->filter(function ($v)
                {
                if ($v->status_id && $v->status_id != 0) {
                    fail("单据{$v->code}{$v->status->name},审核失败!");
                    }
                auditSave($v);
                $v->details->filter(function ($vv)
                    {
                    auditSave($vv);

                    $vv->packs->filter(function ($vvv) use ($vv)
                        {
                        if ($vvv->is_wip != 1) {
                            $vvv->setWhere(
                                [
                                    'batchno'     => $vvv->batchno,
                                    'type_id'     => $vv->type_id,
                                    'reel'        => $vvv->reel,
                                    'location_id' => $vvv->location_id,
                                ]
                            )->useStorage('零售发货', $vv->code)->subStorage();
                            }
                        else {
                            ProProcessesWipRepository::run("subWipStorage", [$vvv->wip_id, $vvv->quantity]);
                            }
                        });

                    });

                });
        }

    protected function noaudit()
        {
        $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })->get()->filter(function ($v)
                {
                if ($v->status_id && $v->status_id != 1) {
                    fail("单据{$v->code}{$v->status->name},审核失败!");
                    }
                auditSave($v, false);
                $v->details->filter(function ($vv)
                    {

                    auditSave($vv, false);
                    $vv->packs->filter(function ($vvv)
                        {
                        if ($vvv->is_wip != 1) {
                            $vvv->nosubStorage()->nouseStorage();
                            }
                        else {
                            ProProcessesWipRepository::run("restoreWip", [$vvv->wip_id, $vvv->quantity]);
                            }
                        });

                    });

                });
        }
    protected function delete()
        {
        return $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })->get()->filter(function ($v)
                {
                if ($v->status_id != 0) {
                    fail("单据{$v->code}{$v->status->name},删除失败!");
                    }
                $v->details->filter(function ($vv)
                    {
                    $vv->packs->filter(fn($vvv) => $vvv->delete());
                    $vv->delete();
                    });
                //删除附件
                $this->repository->deleteAttachment($v)->delete();
                });

        }
    protected function finance()
        {
        $list    = $this->details->whereIn("id", $this->getRequestIds())->get();
        $red_ids = $list->pluck("main_id");
        $codes   = $list->pluck("code");
        // DB::enableQueryLog();
        $this->repository->whereIn("code", $codes)->finance();
        // dd(DB::getQueryLog());1
        MarketComplaintRepository::whereIn("id", $red_ids)->finance();
        }
    public function printReport()
        {
        $res = [];
        $rows = $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })
            ->first();
            
        $rows->details->filter(function ($v) use (&$res, $rows)
                {
                $v->material;
                $v->customer;
                $i                  = 0;
                $k                  = count($res);
                $row                = null;
                $quantity           = 0;
                $auxiliary_quantity = 0;
                $v->packs->filter(function ($vv) use (&$v, &$i, &$k, &$row, &$res, &$quantity, &$auxiliary_quantity)
                    {
                    $auxiliary_quantity++;
                    if ($row == null) {
                        $row = $vv->toArray();
                        }
                    $row['Column' . ($i++)] = (int) $vv->quantity;
                    $quantity += (int) $vv->quantity;
                    if ($i == 10) {
                        $row['auxiliary_quantity'] = $auxiliary_quantity;
                        $row['quantity']           = $quantity;
                        $res[$k++]                 = array_merge($v->toArray(), $row);
                        $auxiliary_quantity        = $quantity = $i = 0;
                        $row = null;
                        }
                    });
            
                if ($i < 9 && $row) {
                    $row['auxiliary_quantity'] = $auxiliary_quantity;
                    $row['quantity']           = $quantity;
                    $res[]                     = array_merge($v->toArray(), $row, ['order_remark'  => $rows->remark]);
                    }
                });
       
        return createReport($res);
        }
    }